package com.example.parkingsharing

import java.sql.Connection
import java.sql.DriverManager

class DatabaseManager {
    companion object {
        const val URL = "jdbc:mysql://47.243.249.75:52533/ShareParking"
        const val USER = "android"
        const val PASSWORD = "kWoHqmDCsVC0opi8k1uj"
        const val TABLE = "parking"
    }

    private val conn: Connection

    init {
        Class.forName("com.mysql.jdbc.Driver")
        conn = DriverManager.getConnection(URL, USER, PASSWORD)
    }

    fun get(): List<DatabaseData> {
        val result = mutableListOf<DatabaseData>()
        val rs = conn.createStatement().executeQuery("select * from $TABLE")
        while (rs.next()) {
            val location = rs.getString("location").split(",")
            val latitude = location[0].toDouble()
            val longitude = location[1].toDouble()
            val booker = rs.getString("booker")
            val publisher = rs.getString("publisher")
            val timestamp = rs.getTimestamp("timestamp")
            val data = DatabaseData(latitude, longitude, booker, publisher, timestamp)
            result.add(data)
        }
        return result.toList()
    }

    fun add(data: DatabaseData) {
        conn.createStatement().execute(
            "insert into $TABLE\n" +
                    "(location,booker,publisher,timestamp)\n" +
                    "values\n" +
                    "('${data.latitude},${data.longitude}','${data.booker}','${data.publisher}','${data.timestamp}');"
        )
    }

    fun del(location: String) {
        conn.createStatement().execute("delete from $TABLE where location='$location'")
    }

    fun update(location: String, data: DatabaseData) {
        del(location)
        add(data)
    }
}